<!DOCTYPE html>
<html>
  <head>
	<title>Reproductor de Audio - Youtube (Beta v1.0)</title>
	<link rel="shortcut icon" href="./images/icon.ico">
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">
	<!-- JQUERY UI -->
	<script src="./js/jquery-1.10.2.js"></script>
	<script src="./js/ui/jquery-ui.js"></script>
	<script src="./js/ui/jquery.ui.datepicker-es.js"></script>
	<script src="./js/jquery.layout.js"></script>
	<!-- JQUERY SWITCH BUTTON -->
	<script src="./js/jquery.switchButton.js"></script>
	<!-- JQGRID -->
	<script src="./js/jquery.jqGrid.min.js"></script>
	<script src="./js/jquery.tablednd.js"></script>
	<script src="./js/grid.locale-en.js"></script>
	<!-- CONTEXT MENU -->
	<script src="./js/jquery.contextMenu.js"></script>
	<script src="./js/ui/ui.multiselect.js"></script>
	<!-- UTILS -->
	<script src="./js/jquery.cookie.js"></script>
	<script src="./js/jquery.json-2.3.min.js"></script>
	<!-- JQUERY PLAYER -->
	<script src="./js/jquery.jplayer.min.js"></script>
	<script src="./js/popcorn.js"></script>
	<!-- NOTIFY JQUERY PLUGIN -->
	<script type="text/javascript" src="./js/noty/jquery.noty.js"></script>
	<script type="text/javascript" src="./js/noty/layouts/top.js"></script>
	<script type="text/javascript" src="./js/noty/themes/default.js"></script>
	<script type="text/javascript" src="./js/nprogress.js"></script>
	<!-- CUSTOM SCROLLBAR PLUGIN -->
	<script type="text/javascript" src="./js/jquery.mousewheel.min.js"></script>
	<script type="text/javascript" src="./js/jquery.mCustomScrollbar.concat.min.js"></script>

	<!--[if lt IE 9]>
	<script src="./js/html5.js"></script>
	<![endif]-->

	<link rel="stylesheet" href="./css/jquery.ui.all.css" />
	<link rel="stylesheet" href="./css/jquery.switchButton.css" />
	<link rel="stylesheet" href="./css/ui.jqgrid.css" />
	<link rel="stylesheet" href="./css/jplayer.blue.monday.css" />
	<link rel="stylesheet" href="./css/jquery.contextMenu.css" />
	<link rel="stylesheet" href="./css/yumiusik.css" />
	<link rel="stylesheet" href="./css/nprogress.css" />
	<link rel="stylesheet" href="./css/jquery.mCustomScrollbar.css" />

	</head>
	<body class="content-body">
		<div id="msg" style="font-size:largest;">
		<!-- you can set whatever style you want on this -->
		<img src="./images/logo.png" width="74" height="74" />Cargando, por favor espere...<img src="./images/waiting.gif" width="30" height="30" />
		</div>
		<div id="body" style="display:none;">
			<div id="tabs">
				<ul>
					<li><a href="#tabs-1">Reproductor (Beta v1.0)</a></li>
				</ul>
				<div id="tabs-1">
					<div id="player">
						<table cellspacing="5px" cellpadding="3px" width="100%">
							<tr>
								<td>
									<table>
										<tr>
											<td>
												<img src="./images/logo.png" width="74" height="74" />
											</td>
											<td>
												<div id="waiting_play"></div>
											</td>
										</tr>
									</table>
								</td>
								<td colspan="2" align="right" style="padding-right: 90px">
								<table>
									<tr>
										<td>
											<table id="saveListTable">
												<tr>
													<td>
														<h3>Grabar Listas</h3>
													</td>
													<td>
														<ul id="icons" class="icons ui-widget ui-helper-clearfix">
															<li class="ui-state-default ui-corner-all" title="Guardar Listas" onclick="javascript:saveAllPlayList();">
																<span class="ui-icon ui-icon-disk"></span>
															</li>
														</ul>
													</td>
												</tr>
											</table>
										</td>
										<td>
											<fieldset id="fldLogin" style="width: 250px;">
												<legend><label for="btnLogin"><span id="btnLogin"><img alt="Login" src="./images/login_key.png" width="16" height="16" />Usuario</span></label></legend>
												<table style="width : 100%">
													<tr>
														<td align="center">
														<table cellspacing="5px" cellpadding="3px" >
															<tr>
																<td rowspan="2">
																	<img alt="Usuario" src="./images/default-user.png" height="55" width="55">
																</td>
																<td>
																	<div id="user_username">Default</div>
																</td>
															</tr>
															<tr>
																<td>
																	<div id="user_name">Usuario Invitado</div>
																</td>
															</tr>
														</table>
														</td>
													</tr>
												</table>
											</fieldset>
										</td>
									</tr>
								</table>
								</td>
							</tr>
							<tr>
								<td>
									<table>
									<tr>
										<td>
											<h3>Reproductor de Audio</h3>
										</td>
									</tr>
									<tr>
										<td valign="top">
			                            	<table>
			                                <tr>
			                                	<td>
			                                		<table>
			                                			<tr>
			                                				<td>
			                                					<table>
			                                						<tr>
			                                							<td>
									                                		<div id="playing_image">
									                                			<img width="120" height="100" src="./images/no_file_music.png">
									                                		</div>
			                                							</td>
			                                							<td>
																			&nbsp;
			                                							</td>
			                                							<td align="center">
																			<p>
																				<label for="amount">Volumen:</label>
																				<input type="text" id="amount" style="border: 0; color: #f6931f; font-weight: bold; width: 20px;"/>
																			</p>
									                                		<div id="slider-vertical" style="height: 80px;"></div>
			                                							</td>
			                                						</tr>
			                                					</table>
			                                				</td>
			                                			</tr>
			                                			<tr>
			                                				<td colspan="2">
						                                        <div id="jquery_jplayer_1" class="jp-jplayer"></div>
						                                        <div id="jp_container_1" class="jp-audio">
						                                            <div class="jp-type-playlist">
						                                                <div class="jp-gui jp-interface">
						                                                    <ul class="jp-controls">
						                                                    	<li><a href="javascript:;" class="jp-previous" tabindex="1">previous</a></li>
						                                                        <li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li>
						                                                        <li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li>
						                                                        <li><a href="javascript:;" class="jp-next" tabindex="1">next</a></li>
						                                                        <li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li><!--
						                                                        <li><a href="javascript:;" class="jp-mute" tabindex="1" title="mute">mute</a></li>
						                                                        <li><a href="javascript:;" class="jp-unmute" tabindex="1" title="unmute">unmute</a></li>
						                                                        <li><a href="javascript:;" class="jp-volume-max" tabindex="1" title="max volume">max volume</a></li>-->
						                                                    </ul>
						                                                    <div class="jp-progress">
						                                                        <div class="jp-seek-bar">
						                                                            <div class="jp-play-bar"></div>
						                                                        </div>
						                                                    </div><!-- 
						                                                    <div class="jp-volume-bar">
						                                                        <div class="jp-volume-bar-value"></div>
						                                                    </div>-->
						                                                    <div class="jp-current-time"></div>
						                                                    <div class="jp-duration"></div>
						                                                </div>
						                                                <div class="jp-title" id="jp-title">
						                                                    <ul>
						                                                        <li>&nbsp;</li>
						                                                    </ul>
						                                                </div>
						                                                <div class="jp-no-solution">
						                                                    <span>Update Required</span>
						                                                    To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.
						                                                </div>
						                                            </div>
						                                        </div>
			                                				</td>
			                                			</tr>
			                                		</table>
			                                    </td>
			                                </tr>
			                                <tr>
			                                	<td>&nbsp;
			                                    	
			                                    </td>
			                                </tr><!--
			                                <tr>
			                                	<td>
													<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.facebook.com%2Fyumiusik&amp;layout=button_count&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:110px; height:21px;" allowTransparency="true"></iframe>
			                                        <a href="http://www.facebook.com/yumiusik/" target="_blank">
			                                        	<img src="./images/facebook.png" width="94" height="35" />
			                                        </a>
			                                    </td>
			                                </tr>-->
			                                </table>
										</td>
									</tr>
									</table>
								</td>
								<td>&nbsp;
									
								</td>
								<td valign="top">
                                	<div class="div-container">
                                		<div id="div-options">
                                			<h3>Listas de Reproducci&oacute;n</h3>
	                                		<div id="tabs-1">
												<div id="subtabs" >
	                                			<ul>
	                                			</ul>
													
												</div>
											</div>
											<h3 id="h_buscar">Buscador de Canciones</h3>
											<div id="buscador">
												<table cellspacing="0" cellpadding="0">
													<tr>
														<td colspan="3">
															<table id="search_info">
																<tr>
																	<td>Buscar</td>
																	<td><input type="text" id="q" name="q" size="150" style="width: 250px"/></td>
																	<td>
																		<ul id="icons" class="ui-widget ui-helper-clearfix">
								                                        	<li class="ui-state-default ui-corner-all" title="Buscar" onclick="javascript:buscar();">
								                                          	  <span class="ui-icon ui-icon-search"></span>Buscar
								                                            </li>
								                                        	<li class="ui-state-default ui-corner-all" title="Limpiar" onclick="javascript:limpiar();">
								                                          	  <span class="ui-icon ui-icon-document"></span>Limpiar
								                                            </li>
																		</ul>
								                                    </td>
																</tr>
															</table>
														</td>
													</tr>
													<tr>
														<td colspan="3" align="right">
															<table>
																<tr>
																	<td id="search-previous-up">&nbsp;
																		
																	</td>
																	<td id="search-next-up">&nbsp;
																		
																	</td>
																</tr>
															</table>
														</td>
													</tr>
													<tr>
														<td colspan="3">
															<table id="data-grid-search"></table>
														</td>
													</tr>
													<tr>
														<td colspan="3" align="right">
															<table>
																<tr>
																	<td id="search-previous-down">&nbsp;
																		
																	</td>
																	<td id="search-next-down">&nbsp;
																		
																	</td>
																</tr>
															</table>
														</td>
													</tr>
												</table>
											</div>
											<h3>Opciones de Reproducci&oacute;n</h3>
		                                	<div id="jplayer-controls">
		                                	<table>
		                                	<tr>
		                                		<td colspan="3">
	                   								<div id="player_equalize">
	                   								</div>
		                                		</td>
		                                	</tr>
		                                	<tr class="switch-button-label on">
		                                		<td style="width: 120px;">
		                                			<fieldset id="field_repeat" style="padding: 10px">
		                                				<legend>Repetir</legend>
				                                    	<div id="div_repeat">
				                                    		<input name="repeat" id="repeat" type="checkbox" value="1">
				                                    	</div>
		                                			</fieldset>
		                                		</td>
		                                		<td>&nbsp;&nbsp;&nbsp;</td>
		                                		<td style="width: 120px;">
		                                			<fieldset id="field_shuffle" style="padding: 10px">
		                                			<legend>Aleatorio</legend>
			                                    	<div id="div_shuffle">
			                                    		<input name="shuffle" id="shuffle" type="checkbox" value="1">
			                                    	</div>
			                                    	</fieldset>
		                                		</td>
		                                	</tr>
		                                	</table>
		                                    </div>
		                                    <h3 id="shared_h3">Lista Compartidos</h3>
		                                    <div id="sharedList">
		                                    	<table id="data-grid-shared"></table>
		                                    	<div id="paginacion-shared"></div>
		                                    </div>
										</div>
                                	</div>
								</td>
							</tr>
						</table>
	                    <br/>
	                    <table cellpadding="0" cellspacing="0" border="0" width="100%">
	                        <tr>
	                            <td>
	                                &copy; 2013 <a href="#" target="_blank" style="color: red;">YurCompany SAC</a>, Todos los derechos reservados.
	                            </td>
	                        </tr>
	                    </table>
					</div>
				</div>
			</div>
			<div id="messageDIV" title="Mensaje">
				<p>Espere mientras el servidor procesa su requerimiento...</p>
			</div>
			<div id="confirmDIV" title="&#191;Desea eliminar el item?">
			  <p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>Despues de eliminar el item no se podra recuperar. &#191;Esta seguro de eliminar?</p>
			</div>
			<div id="newTabDIV" title="Lista de Reproduccion">
				<form>
					<fieldset class="ui-helper-reset">
						<label for="tab_title">Nombre</label>
						<input type="text" name="tab_title" id="tab_title" value="" class="ui-widget-content ui-corner-all" />
					</fieldset>
				</form>
			</div>
			<div id="loginDIV" title="Login">
				<form>
					<table width="100%" border="0" cellspacing="0" cellpadding="5">
						<tr>
							<td width="15%"><label for="username">Username</label></td>
							<td width="70%">
								<input type="text" name="username" id="username" value="" class="ui-widget-content ui-corner-all" />
							</td>
							<td width="15%" id="errOffset">&nbsp;</td>
						</tr>
						<tr>
							<td><label for="password">Password</label></td>
							<td>
								<input type="password" name="password" id="password" value="" class="ui-widget-content ui-corner-all" />
							</td>
							<td>&nbsp;</td>
						</tr>
						<tr>
							<td colspan="3">
								&nbsp;
							</td>
						</tr>
						<tr>
							<td colspan="3">
								<span id="btnRegister"><img alt="Registrar" src="./images/add_user.png" width="16" height="16" />Nuevo Usuario</span>
							</td>
						</tr>
					</table>
				</form>
			</div>
			<div id="registerDIV" title="Registro de Usuario">
				<form>
					<fieldset class="ui-helper-reset">
						<table>
							<tr>
								<td>
									<label for="userRegister">Username</label>
									<input type="text" name="userRegister" id="userRegister" value="" class="ui-widget-content ui-corner-all" />
								</td>
							</tr>
							<tr>
								<td>
									<label for="passRegister">Password</label>
									<input type="password" name="passRegister" id="passRegister" value="" class="ui-widget-content ui-corner-all" />
								</td>
							</tr>
						</table>
					</fieldset>
				</form>
			</div>
			<div id="changeListDIV" title="Cambio de Lista">
				<ol id="changeListControl">
				</ol>
			</div>
			<div id="shareDIV" title="Compartir">
				<ol id="shareList">
					<li id="share_email" class="ui-widget-content"><img alt="email" src="./images/share_email.png" width="40px" height="40px" /> EMAIL</li>
					<li id="share_facebook" class="ui-widget-content"><img alt="facebook" src="./images/share_facebook.png" width="40px" height="40px" /> FACEBOOK</li>
					<li id="share_tweeter" class="ui-widget-content"><img alt="tweeter" src="./images/share_tweeter.png" width="40px" height="40px" /> TWEETER</li>
				</ol>
			</div>
			<div id="shareEmailDIV" title="Email">
				<form>
					<fieldset class="ui-helper-reset">
						<table>
							<tr>
								<td>
									<label for="userFrom">De</label>
									<input type="text" name="userFrom" id="userFrom" value="" class="ui-widget-content ui-corner-all" />
								</td>
							</tr>
							<tr>
								<td>
									<label for="userTo">Para</label>
									<input type="text" name="userTo" id="userTo" value="" class="ui-widget-content ui-corner-all" />
								</td>
							</tr>
							<tr id="messageTR">
								<td>
									<label for="userTo">Mensaje</label>
									<textarea name="message" id="message" class="ui-widget-content ui-corner-all"></textarea>
								</td>
							</tr>
						</table>
					</fieldset>
				</form>
			</div>
			<div id="userDetailDIV" title="Perfil Usuario">
				<form>
					<fieldset class="ui-helper-reset">
						<table>
							<tr>
								<td>
									<label for="userFrom">Nombres</label>
									<input type="text" name="nombres" id="nombres" value="" class="ui-widget-content ui-corner-all" />
								</td>
							</tr>
							<tr>
								<td>
									<label for="userTo">Apellidos</label>
									<input type="text" name="apellidos" id="apellidos" value="" class="ui-widget-content ui-corner-all" />
								</td>
							</tr>
							<tr>
								<td>
									<label for="userTo">Fecha Nacimiento</label>
									<input type="text" name="nacimiento" id="nacimiento" value="" class="ui-widget-content ui-corner-all" />
								</td>
							</tr>
						</table>
					</fieldset>
				</form>
			</div>
		</div>
		<script type="text/javascript">
		// AjaxPrefilter para no tener problemas con el crossDomain
		$.ajaxPrefilter(function(options) {
		  if(options.crossDomain && jQuery.support.cors) {
		    var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
		    options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
		  }
		});
		$(document).ready(function() {
		    $('#body').show();
		    $('#msg').hide();
			var icons = {
				header: "ui-icon-triangle-arrow-e",
				activeHeader: "ui-icon-triangle-arrow-s"
				};
			$( "#div-options" ).accordion({
				icons: icons,
				heightStyle: "content",
				header: "h3"
			});
			$( "#shared_h3" ).hide();
			$( "#user_name" ).mouseover(function() {
				if(userCode != -1){
					$( "#user_name" ).effect( "highlight", {}, 5000, function(){} );
				}
			}).click(function(){
				if(userCode != -1){
					$( "#userDetailDIV" ).dialog('open');
				}
			});
			$( "#nacimiento" ).datepicker($.datepicker.regional[ "es" ]);
		});
		</script>

        <script type='text/javascript'>
			$('#player_user_information');
			$('#saveListTable').hide();
        </script>
        <script type='text/javascript'>
			var audioContext;
			var gainNode;
			var audioPlayer;
			var filterArray = new Array();
			var equalizeFrequencies = [80, 240, 750, 2200, 6000];
			try {
				// Fix up for prefixing
				window.AudioContext = window.AudioContext||window.webkitAudioContext;
				audioContext = new AudioContext();
			}
			catch(e) {
				$(function(){
					noty({
						text        : 'Su navegador no soporta [Web Audio API] por eso no se va a mostrar el equalizador, haga click para cerrar este mensaje',
						type        : 'warning',
						dismissQueue: true,
						layout      : 'top',
						timeout		: 3000
					});
				});
			}
			var isChrome = window.chrome;
			if(isChrome){
				if(audioContext){
					if (!audioContext.createGain){
						audioContext.createGain = audioContext.createGainNode;
					}
					gainNode = audioContext.createGain();
	
					// filling filterArray
					$("#player_equalize").append("<table id=\"table_eq\" style=\"border: 2px solid orange;\"></table>");
					$("#table_eq").append("<tr id=\"table_tr_val_eq\"></tr>");
					$("#table_eq").append("<tr id=\"table_tr_eq\"></tr>");
					$("#table_eq").append("<tr id=\"table_tr_fq_eq\"></tr>");
					for(var i = 0; i < equalizeFrequencies.length; i++){
						var fq = equalizeFrequencies[i];
						var filter = audioContext.createBiquadFilter();
						var _gain = (i == 0 ? null : 0);
						filter.type = "peaking";
						filter.gain.value = _gain;
						filter.Q.value = 1;
						filter.frequency.value = fq;
						filterArray.push(filter);
	
						var filterName = 'filter' + fq + 'Hz';
						var valueTD = 'val_' + fq;
						$("#table_tr_val_eq").append("<td id=\"val_"+fq+"\" align=\"center\">0.00 db</td>");
						$("#table_tr_eq").append( "<td align=\"center\" style=\"text-align: center; padding: 0.9em; border: 2px solid orange;\"><div id='" + filterName + "' style=\"height: 60px;\"/></td>" );
						var slider = {
							'orientation': "vertical",
							'range': "min",
							'min': -30,
							'max': 30,
							'animate': true,
							'step': 0.01,
							'slide': function(event, ui) {
								var _id = this.id;
								var fq = parseInt(_id.replace('filter','').replace('Hz',''));
								var index = 0;
								for(var i = 0; i < equalizeFrequencies.length; i++){
									if(equalizeFrequencies[i] == fq){
										index = i;
										break;
									}
								}
								filterArray[index].gain.value = ui.value;
							},
							'stop': function(event, ui) {
								var _id = this.id;
								var fq = parseInt(_id.replace('filter','').replace('Hz',''));
								var index = 0;
								for(var i = 0; i < equalizeFrequencies.length; i++){
									if(equalizeFrequencies[i] == fq){
										index = i;
										break;
									}
								}
								var value = Math.round(filterArray[index].gain.value).toFixed(2);
								var vw = "val_"+fq;
								$("#"+vw).html(value+" db");
								console.log(filterArray[index].gain.value);
							}
						};
						$('#'+filterName).slider(slider);
						$("#table_tr_fq_eq").append("<td align=\"center\"><label for=\""+filterName+"\">"+fq+" Hz</label></td>");
					}
				}				
			}
        </script>
		<script type='text/javascript'>
			$(function(){
		        $("#div_repeat input").switchButton({
		          on_label: 'SI',
		          off_label: 'NO'
		        });

		        $("#div_shuffle input").switchButton({
		          on_label: 'SI',
		          off_label: 'NO'
		        });

				$( "#slider-vertical" ).slider({
					orientation: "vertical",
					range: "min",
					min: 0,
					max: 100,
					value: 80,
					slide: function( event, ui ) {
						var valor = parseInt(ui.value);
						$( "#amount" ).val( valor );
						$("#jquery_jplayer_1").jPlayer("volume", (valor / 100));
						if(gainNode){
							gainNode.gain.value = valor / 100;
						}
					}
				});
				$( "#amount" ).val( $( "#slider-vertical" ).slider( "value" ) );
			});
			var _numberList = 0;
			var gridList = [];
			var tabList = [];
			var tipo_tab = 'nuevo';
			var tipo_eliminar;
			var tipo_share;
			var pointer;
			var toEdit = '';
			var repeat = $( "#repeat" );
			var shuffle = $( "#shuffle" );
			var messageDialog = $("#messageDIV").dialog({
				height: 180,
				modal: true,
				autoOpen: false
			});
			var confirmDialog = $("#confirmDIV").dialog({
				resizable: false,
				height: 160,
				modal: true,
				autoOpen: false,
				buttons: {
					"Eliminar": function() {
						tipo_eliminar.call();
						$( this ).dialog( "close" );
					},
					Cancelar: function() {
						$( this ).dialog( "close" );
					}
				}
			});
			function createNewList(){
				_numberList = parseInt(_numberList) + 1;
				addList(_numberList);
			}
			function updateList(){
				_listnames[_selectPlayList] = $( "#tab_title" ).val();
				$(toEdit).text($( "#tab_title" ).val());
			}
			var newTabDialog = $( "#newTabDIV" ).dialog({
				autoOpen: false,
				modal: true,
				buttons: {
					Ok: function() {
						if(tipo_tab == 'nuevo'){
							createNewList();
						}else{
							updateList();
						}
						$( this ).dialog( "close" );
					},
					Cancelar: function() {
						$( this ).dialog( "close" );
					}
				},
				close: function() {
					$( "#tab_title" ).val('');
				}
			});
			$("#tab_title").keypress(function(event) {
	  			if ( event.which == 13 ) {
					if(tipo_tab == 'nuevo'){
						createNewList();
					}else{
						updateList();
					}
					newTabDialog.dialog( "close" );
				}else{
					if ( event.keyCode == 13 ){
						if(tipo_tab == 'nuevo'){
							createNewList();
						}else{
							updateList();
						}
						newTabDialog.dialog( "close" );
					}else{
						if ( event.charCode == 13 ){
							if(tipo_tab == 'nuevo'){
								createNewList();
							}else{
								updateList();
							}
							newTabDialog.dialog( "close" );
						}
					}
				}
			});
			var loginDialog = $( "#loginDIV" ).dialog({
				autoOpen: false,
				modal: true,
				buttons: {
					Ok: function() {
						loginFnc();
						$( this ).dialog( "close" );
					},
					Cancelar: function() {
						$( this ).dialog( "close" );
					}
				},
				close: function() {
					$( "#username" ).val('');
					$( "#password" ).val('');
				}
			});
			var registerDialog = $( "#registerDIV" ).dialog({
				autoOpen: false,
				modal: true,
				buttons: {
					Ok: function() {
						registerFnc();
						$( this ).dialog( "close" );
					},
					Cancelar: function() {
						$( this ).dialog( "close" );
					}
				},
				close: function() {
					$( "#userRegister" ).val('');
					$( "#passRegister" ).val('');
				}
			});
			var changeListDialog = $( "#changeListDIV" ).dialog({
				autoOpen: false,
				modal:true,
				buttons: {
					Ok: function() {
						completeChange();
						$( this ).dialog( "close" );
					},
					Cancelar: function() {
						$( this ).dialog( "close" );
					}
				}
			});
			var shareListDialog = $( "#shareDIV" ).dialog({
				autoOpen: false,
				modal: true
			});
			var shareEmailDialog = $( "#shareEmailDIV" ).dialog({
				autoOpen: false,
				modal: true,
				buttons: {
					Ok: function(){
						tipo_share.call();
					},
					Cancelar: function(){
						$( this ).dialog( "close" );
					}
				},
				close: function() {
					$( "#userFrom" ).val('');
					$( "#userTo" ).val('');
					$( "#message" ).val('');
				}
			});
			var userDetailDialog = $( "#userDetailDIV" ).dialog({
				autoOpen: false,
				modal: true,
				buttons: {
					Ok: function(){
						saveUserDetail();
					},
					Cancelar: function(){
						$( this ).dialog( "close" );
					}
				},
				close: function() {
					$( "#nombres" ).val('');
					$( "#apellidos" ).val('');
					$( "#nacimiento" ).val('');
				}
			});
			var changeListControl = $("#changeListControl").selectable({
				stop: function() {
				  $( ".ui-selected", this ).each(function() {
				  	var _id = this.id;
				    var codigo = _id.split("_")[1];
				    change['target'] = codigo;
				    change['source'] = _selectPlayList;
				  });
				}
			});
			var shareControl = $("#shareList").selectable({
				stop: function() {
				  $( ".ui-selected", this ).each(function() {
				  	var _id = this.id;
				  	var type = _id.split("_")[1];
				    if(type == 'email'){
						$( "#shareEmailDIV" ).dialog( "open" );				    	
				    }
				    if(type == 'facebook'){
						$(function(){
							noty({
								text        : 'PROXIMAMENTE...',
								type        : 'information',
								dismissQueue: true,
								layout      : 'top',
								timeout		: 3000
							});
						});
				    }
				    if(type == 'tweeter'){
						$(function(){
							noty({
								text        : 'PROXIMAMENTE...',
								type        : 'information',
								dismissQueue: true,
								layout      : 'top',
								timeout		: 3000
							});
						});	
				    }
				    $('#shareList .ui-selected').removeClass('ui-selected');
				    $( "#shareDIV" ).dialog( "close" );
				  });
				}
			});
			var form = newTabDialog.find( "form" ).submit(function( event ) {
				newTabDialog.dialog( "close" );
				event.preventDefault();
			});
			var formLogin = loginDialog.find( "form" ).submit(function( event ) {
				loginDialog.dialog( "close" );
				event.preventDefault();
			});
			var formRegister = registerDialog.find( "form" ).submit(function( event ) {
				registerDialog.dialog( "close" );
				event.preventDefault();
			});
			var formShareEmail = shareEmailDialog.find( "form" ).submit(function( event ) {
				shareEmailDialog.dialog( "close" );
				event.preventDefault();
			});
			$("#username").keypress(function(event) {
	  			if ( event.which == 13 ) {
					loginFnc();
				}else{
					if ( event.keyCode == 13 ){
						loginFnc();
					}else{
						if ( event.charCode == 13 ){
							loginFnc();
						}
					}
				}
			});
			$("#password").keypress(function(event) {
	  			if ( event.which == 13 ) {
					loginFnc();
				}else{
					if ( event.keyCode == 13 ){
						loginFnc();
					}else{
						if ( event.charCode == 13 ){
							loginFnc();
						}
					}
				}
			});
			$("#userRegister").keypress(function(event) {
	  			if ( event.which == 13 ) {
					registerFnc();
				}else{
					if ( event.keyCode == 13 ){
						registerFnc();
					}else{
						if ( event.charCode == 13 ){
							registerFnc();
						}
					}
				}
			});
			$("#passRegister").keypress(function(event) {
	  			if ( event.which == 13 ) {
					registerFnc();
				}else{
					if ( event.keyCode == 13 ){
						registerFnc();
					}else{
						if ( event.charCode == 13 ){
							registerFnc();
						}
					}
				}
			});
			$("#userFrom").keypress(function(event) {
	  			if ( event.which == 13 ) {
					tipo_share.call();
				}else{
					if ( event.keyCode == 13 ){
						tipo_share.call();
					}else{
						if ( event.charCode == 13 ){
							tipo_share.call();
						}
					}
				}
			});
			$("#userTo").keypress(function(event) {
	  			if ( event.which == 13 ) {
					tipo_share.call();
				}else{
					if ( event.keyCode == 13 ){
						tipo_share.call();
					}else{
						if ( event.charCode == 13 ){
							tipo_share.call();
						}
					}
				}
			});
			$("#message").keypress(function(event) {
	  			if ( event.which == 13 ) {
					tipo_share.call();
				}else{
					if ( event.keyCode == 13 ){
						tipo_share.call();
					}else{
						if ( event.charCode == 13 ){
							tipo_share.call();
						}
					}
				}
			});
			$( "#btnLogin" ).button().click(function() { if(!_login){ loginDialog.dialog( "open" ); }else{ logoutFnc(); }});
			$( "#btnRegister" ).button().click(function() {registerDialog.dialog( "open" );});
		</script>
	<script type='text/javascript'>
		var _selectPlayList = 0;
		var userCode = $.cookie("_3tperu_cookie_userCode") ? $.cookie("_3tperu_cookie_userCode") : -1;
		var userInformation = {};
		var _playList = {};
		var _login = false;
		var image_played = '';
		var change = {};
		var share_link = '';
		var share_idList = '';
		for(var i = 0; i <= _numberList; i++){
			_playList['list_'+i] = [];
		}
		var _codeList = ['-1'];
		var _listnames = ['Lista Principal'];
		<%if((Boolean)request.getAttribute("autoPlayList")){ %>
			<% java.util.Map<String, Object> info = (java.util.Map<String, Object>)request.getAttribute("playListAuto");
				String listname = (String)info.get("LIST_NAME");
				java.util.List<java.util.Map<String, Object>> songList = (java.util.List<java.util.Map<String, Object>>)info.get("SONG_LIST");
				java.util.List<java.util.Map<String, Object>> nlist = new java.util.ArrayList<java.util.Map<String, Object>>();
				for(int i = 0;i < songList.size(); i++){
					java.util.Map<String, Object> item = new java.util.HashMap<String, Object>();
					java.util.Map<String, Object> actual = songList.get(i);
					item.put("codigo", "http://gdata.youtube.com/feeds/api/videos/" + actual.get("codigo"));
					item.put("code", actual.get("code"));
					item.put("link", actual.get("link"));
					item.put("nombre", actual.get("title"));
					item.put("imagen", "<img width=\"120\" heigth=\"100\" src=\""+actual.get("image_link")+"\">");
					item.put("segundos", actual.get("segundos"));
					int segundosTotales = Integer.parseInt(String.valueOf(actual.get("segundos")));
					int horas = segundosTotales / 3600;
					int resto = segundosTotales % 3600;
					int minutos = resto / 60;
					int segundos = resto % 60;
					String duracion = (horas < 10 ? "0" : "")+horas + ":" + (minutos < 10 ? "0" : "") + minutos + ":" + (segundos < 10 ? "0" : "") + segundos;
					item.put("duracion", duracion);
					item.put("agregar", "<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Agregar\" onclick=\"javascript:addToPlayList('"+i+"')\"><span class=\"ui-icon ui-icon-plusthick\"></span></li></ul>");
					item.put("play","<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Escuchar\" onclick=\"javascript:play('"+i+"')\"><span class=\"ui-icon ui-icon-play\"></span></li></ul>");
					item.put("remove","<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Quitar\" onclick=\"javascript:removeFromPlayList("+i+")\"><span class=\"ui-icon ui-icon-trash\"></span></li></ul>");
					nlist.add(item);
				}
			%>
			_playList['list_0'] = <%=(new com.fasterxml.jackson.databind.ObjectMapper()).writeValueAsString(nlist)%>;
			_listnames[0] = '<%=listname%>';
		<%}%>
		var _data = [];
		var $dgBuscar = $('#data-grid-search');
		var $dgShared = $('#data-grid-shared');

		var tabTitle = $( "#tab_title" );
		var txtUsername = $( "#username" );
		var txtPassword = $( "#password" );
		var txtUsernameRegister = $( "#userRegister" );
		var txtPasswordRegister = $( "#passRegister" );
		var txtUserFrom = $( "#userFrom" );
		var txtUserTo = $( "#userTo" );
		var txtMessage = $( "#message" );
		var tabTemplateFirst = "<li><a href='%{href}' class='lista_reproduccion'>%{label}</a></li>";
		var tabTemplate = "<li><table cellspacing='0' cellpadding='0'><tr><td><a href='%{href}' class='lista_reproduccion'>%{label}</a></td><td><span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></td></tr></table></li>";
		var tabTemplateLast = "<li class='add-tabs-class ui-state-default ui-corner-top ui-tabs-active ui-state-active'><a class='ui-tabs-anchor'><span class='ui-icon ui-icon-plus' role='presentation'>Add Tab</span></a></li>";

		function getUserPart(part){
			return userInformation[part];
		}
		$(document).ready(function() {
			$.ajaxSetup({
				headers: {"X-Requested-With":"XMLHttpRequest"}
			});
			$(function() {
				// configuracion de Tabs
				$( "#tabs, #subtabs" ).tabs();
				
				loadTabs();

				$("#jquery_jplayer_1").jPlayer({
					ended: function() {
						getNextSong();
					},
					preload: "auto",
					solution: "flash, html",
					emulateHtml: true, 
					swfPath: "<%=request.getAttribute("APP_SERVER_URL") %>swf",
					supplied: "mp3",
					wmode: "window",
					progress: function(){
						$("#waiting_play").html('');
						$("#playing_image").html(image_played);
					},
					ready: function (event) {
						$(".jp-toggles").remove();
						$(".jp-next").unbind();
						$(".jp-previous").unbind();
						$(".jp-previous").bind( "click", function() {
							getPreviousSong();
						});
						$(".jp-next").bind( "click", function() {
							getNextSong();
						});
						if(isChrome){
							if(audioContext){
								if(event.jPlayer.html.used && event.jPlayer.html.audio.available) {
									audioPlayer = Popcorn('#' + $(this).data("jPlayer").internal.audio.id);
								}else{
									$(this).jPlayer("option","emulateHtml",true);
									audioPlayer = Popcorn('#' + $(this).attr("id"));
								}
								try{
									var _audio = audioPlayer.audio;
									_audio.ontimeupdate = function(){
										startDrawProgress();
									};
									_audio.preload = 'auto';
									var source = audioContext.createMediaElementSource(_audio);
									source.connect(gainNode);
									gainNode.gain.value = 0.8;
	
									for(var i = 0; i < filterArray.length; i++){
										var filter1 = i > 0 ? filterArray[i - 1] : null;
										var filter2 = filterArray[i];
										if(i == 0){
											gainNode.connect(filter2);
										}else{
											if(filter1 != null){
												filter1.connect(filter2);
											}
										}
									}
									filterArray[filterArray.length -1].connect(audioContext.destination);
	
									audioPlayer.on( "play", function(){
										startDrawProgress();
									});
	
									audioPlayer.on( "stop", function(){
										stopDrawProgress();
									});
								}catch(e){
									$(function(){
										noty({
											text        : e.message,
											type        : 'error',
											dismissQueue: true,
											layout      : 'top'
										});
									});								
								}
							}
						}
				<%if((Boolean)request.getAttribute("autoPlay")){ %>
						<% com.yumiusik.common.domain.AudioInformation audioInformation = (com.yumiusik.common.domain.AudioInformation)request.getAttribute("audioInformation"); %>
						$("#waiting_play").html('<img alt="waiting..." src="./images/waiting.gif" height="30" width="30">');
						image_played = "<img width=\"120\" heigth=\"100\" src=\"<%=audioInformation.getImage() %>\">";
						var url_link = '<%=audioInformation.getLink()%>';
						var mp3 = '<%=request.getAttribute("APP_SERVER_URL") %>mp3low/?url=' + url_link;
						$(this).jPlayer("setMedia", {
							mp3: mp3
						});
						$("#jquery_jplayer_1").jPlayer("play");
						showTitle('<%=audioInformation.getTitle() %>');
				<%} %>
				<%if((Boolean)request.getAttribute("autoPlayList")){ %>
					play(0);
				<%}%>
					}
				});

			    $dgBuscar.jqGrid({
			    	datatype: 'local'
			    	,data: _data
					,pagination: false
					,rowNumber:true
					,multiselect: false
					,height: 180
					,colNames:['Imagen','Nombre', 'Duracion', 'Add']
					,colModel:[{
						index: 'imagen' ,name:'imagen', width:170, align:'center', sortable:false
					},{
						index: 'nombre' ,name:'nombre', width:340, align:'left', sortable:false
					},{
						index: 'duracion' ,name:'duracion', width:90, align:'center', sortable:false
					},{
						index: 'agregar' ,name:'agregar', width:50, align:'center', sortable:false
					}]
					,onSelectRow: function(rowid, status) {
				    	$(this).find(".ui-state-highlight, [aria-selected='true']").removeClass('ui-state-highlight');
					}
				});

				$dgShared.jqGrid({
					url: '<%=request.getAttribute("APP_SERVER_URL") %>getPlayListShared?userID='+getUserPart('EMAIL')
					,mtype: 'POST'
			    	,datatype: 'json'
					,pagination: true
					,rowNumber: true
					,multiselect: false
					,height: 180
					,colNames:['Usuario Origen','Usuario Destino', 'Tipo', 'Titulo', 'Mensaje', 'Forma', 'Enviado', 'Escuchado']
					,colModel:[{
						index: 'USER_FROM' ,name:'USER_FROM', width:100, align:'center', sortable:false
					},{
						index: 'MAIL_TO' ,name:'MAIL_TO', width:100, align:'left', sortable:false
					},{
						index: 'TYPE' ,name:'TYPE', width:70, align:'center', sortable:false
					},{
						index: 'TITLE' ,name:'TITLE', width:90, align:'center', sortable:falsepla
					},{
						index: 'MESSAGE' ,name:'MESSAGE', width:160, align:'center', sortable:false
					},{
						index: 'KIND' ,name:'KIND', width:70, align:'center', sortable:false
					},{
						index: 'SENDED' ,name:'SENDED', width:70, align:'center', sortable:false
					},{
						index: 'LISTENED' ,name:'LISTENED', width:70, align:'center', sortable:false
					}]
					,onSelectRow: function(rowid, status) {
				    	$(this).find(".ui-state-highlight, [aria-selected='true']").removeClass('ui-state-highlight');
					}
					,pager: '#paginacion-shared'
				});

				drawPlayList();
			});
		});
	</script>
	<script type="text/javascript">
		var rowIndexSource;
		var rowIndexTarget;
		function startDrawProgress(){
			var _time = audioPlayer.currentTime();
			var _duration = audioPlayer.duration();
			var progressPercent = parseInt((_time / _duration) * 100);

			console.debug(progressPercent + " %");
			$("#jp-current-time").html(_time);
			$("#jp-play-bar").width(progressPercent+"%");
		}
		function stopDrawProgress(){
			
		}
		function clearTabs(){
			$('div#subtabs ul li').remove();
			$('div#subtabs div').remove();
			$("div#subtabs").tabs("refresh");

			gridList = new Array();
		}
		function loadTabs(){
			for(var i = 0; i <= parseInt(_numberList); i++){
				if(_listnames[i] == undefined || _listnames[i] == '') _listnames.push('Tab ' + (i + 1));
				addList(i);
			}
		}
		function addList(index){
			var tableID = "data-grid-local-"+index;
			gridList.push(tableID);
			var table = document.createElement("table");
			table.setAttribute("id", tableID);

			if(_listnames[index] == undefined || _listnames[index] == '') _listnames.push(tabTitle.val());
			if(_codeList[index] == undefined || _codeList[index] == '') _codeList.push('-1');
			var label = _listnames[index];
			var id = "lista-" + index;
			var li_first = $( tabTemplateFirst.replace( /%\{href\}/g, "#" + id ).replace( /%\{label\}/g, label ) );
			var li = $( tabTemplate.replace( /%\{href\}/g, "#" + id ).replace( /%\{label\}/g, label ) );
			var li_last = $( tabTemplateLast );

			// Remove last tab
			if(index > 0 && !_playList['list_'+index]){
				$("#subtabs").find( "li.add-tabs-class" ).remove();;
			}

			$("#subtabs").find( ".ui-tabs-nav" ).append( index == 0 ? li_first : li );
			$("#subtabs").append( "<div id='" + id + "' />" );
			$("#subtabs").tabs( "refresh" );

			$("#"+id).append(table);
			$("#"+id).mCustomScrollbar({ scrollInertia:600, autoDraggerLength:false, autoHideScrollbar:true, advanced:{ updateOnContentResize: true } });

			$("#subtabs").delegate( "span.ui-icon-close", "click", function() {
				pointer = $( this );
				tipo_eliminar = function(){
					var panelId = pointer.closest( "li" ).remove().attr( "aria-controls" );
					var toDelete = $( "#" + panelId );
					var indice = toDelete.index() - 1;
					delete _playList['list_'+indice];
					_listnames.splice(indice, 1);
					_codeList.splice(indice, 1);
					_numberList = _numberList - 1;
					// Fix delete list from memory
					toDelete.remove();
					$("#subtabs").tabs( "refresh" );
				};
				$("#confirmDIV").dialog('open');
			});

			if(index ==	parseInt(_numberList)){
				$("#subtabs").find( ".ui-tabs-nav" ).append(li_last);
				$("#subtabs").delegate( "span.ui-icon-plus", "click", function() {
					addNewList();
				});
			}

			$("#subtabs").tabs({
				active : 0,
				beforeActivate: function (event, ui) {
					var index = $(ui.newTab).index();
					_selectPlayList = parseInt(index);
				}
			});

			// Context Menu to events on playlist tabs
		    $.contextMenu({
		        selector: '.lista_reproduccion', 
		        callback: function(key, options) {
		        	var attr = options.$trigger.context.attributes;
		        	var href_row = 0;
		        	for(var i = 0; i < attr.length; i++){
		        		var nodeName = attr[i].nodeName;
		        		if(nodeName == 'href'){
		        			href_row  = attr[i].nodeValue;
		        		}
		        	}
		        	var index = parseInt(href_row.replace('#lista-',''));
		        	
		        	if(key == 'edit'){
			        	var href = attr[4];
			        	var _id = href.nodeValue;
			        	toEdit = '#'+_id;
			        	tipo_tab = 'update';
			        	var txt = $(toEdit).text();
			            $("#tab_title").val(txt);
			            newTabDialog.dialog( "open" );
		        	}
		        	if(key == 'save'){
		        		savePlayList(index);
		        	}
		        	if(key == 'share'){
		        		tipo_share = function(){ sendEmailList(); };
		        		var list_code = _codeList[index];
		        		if(list_code != -1){
			        		share_idList = list_code;
			        		if(_login){
			        			txtUserFrom.val(userInformation.EMAIL);
			        		}
			        		$( "#messageTR" ).hide();
			        		$( "#shareDIV" ).dialog('open');
		        		}else{
							$(function(){
								noty({
									text        : 'Solo se pueden compartir listas que se encuentren almacenadas en el servidor',
									type        : 'warning',
									dismissQueue: true,
									layout      : 'top',
									timeout		: 3000
								});
							});
		        		}
		        	}
		        	if(key == 'dedicated'){
		        		tipo_share = function(){ sendEmailList(); };
		        		var list_code = _codeList[index];
		        		if(list_code != -1){
			        		share_idList = list_code;
			        		if(_login){
			        			txtUserFrom.val(userInformation.EMAIL);
			        		}
			        		$( "#messageTR" ).show();
			        		$( "#shareDIV" ).dialog('open');
		        		}else{
							$(function(){
								noty({
									text        : 'Solo se pueden compartir listas que se encuentren almacenadas en el servidor',
									type        : 'warning',
									dismissQueue: true,
									layout      : 'top',
									timeout		: 3000
								});
							});
		        		}
		        	}
		        },
		        items: {
		            "edit": {name: "Editar", icon: "edit"},
		            "save": {name: "Guardar", icon: "save"},
		            "share": {name: "Compartir", icon: "share"},
		            "dedicated": {name: "Dedicar", icon: "dedicated"}
		        },
		        events: {
			        show: function(opt){ 
						var attr = opt.$trigger.context.attributes;
			        	var href_row = 0;
			        	for(var i = 0; i < attr.length; i++){
			        		var nodeName = attr[i].nodeName;
			        		if(nodeName == 'href'){
			        			href_row  = attr[i].nodeValue;
			        		}
			        	}
			        	var index = parseInt(href_row.replace('#lista-',''));
			        	_selectPlayList = index;
			        	$("#subtabs").tabs( "option", "active", _selectPlayList );
			        }
		        }
		    });

			// Context Menu to events on list song
		    $.contextMenu({
		        selector: 'tr .jqgrow', 
		        callback: function(key, options) {
		        	var attr = options.$trigger.context.attributes;
		        	var tabindex = _selectPlayList;
		        	var index_row = 0;
		        	for(var i = 0; i < attr.length; i++){
		        		var nodeName = attr[i].nodeName;
		        		if(nodeName == 'id'){
		        			index_row = attr[i].nodeValue;
		        		}
		        	}
		        	var list = _playList['list_'+tabindex];
		        	var index_select = parseInt(index_row) - 1;
		        	var row = list[index_select];
		        	if(key == 'related'){
		        		var enlace = row.link;
		        		related(enlace);
		        	}
		        	if(key == 'change'){
		        		showChangeList(index_select);
		        	}
		        	if(key == 'share'){
		        		tipo_share = function(){ sendEmail(); };
		        		share_link = row.link;
		        		if(_login){
		        			txtUserFrom.val(userInformation.EMAIL);
		        		}
		        		$( "#messageTR" ).hide();
		        		$( "#shareDIV" ).dialog('open');
		        	}
		        	if(key == 'dedicated'){
		        		tipo_share = function(){ sendEmail(); };
		        		share_link = row.link;
		        		if(_login){
		        			txtUserFrom.val(userInformation.EMAIL);
		        		}
		        		$( "#messageTR" ).show();
		        		$( "#shareDIV" ).dialog('open');
		        	}
		        },
		        items: {
		            "change": {name: "Cambiar de Lista", icon: "list"},
		            "related": {name: "Buscar Relacionados", icon: "related"},
		            "share": {name: "Compartir", icon: "share"},
		            "dedicated": {name: "Dedicar", icon: "dedicated"}
		        }
		    });
			var list = _playList['list_'+index] ? _playList['list_'+index] : [];

			$(table).tableDnD({
				onDragStart : function(table,row){
					rowIndexSource = row.rowIndex - 1;
				},
				onDrop : function(table,row){
					rowIndexTarget = row.rowIndex - 1;
					changePosition();
				}
			});
		    $(table).jqGrid({
		    	datatype: 'local'
		    	,data: list
				,pagination: false
				,rowNumber:true
				,multiselect: false
				,height: 200
				,colNames:['Imagen','Nombre', 'Duracion', 'Play', 'Eliminar']
				,colModel:[{
					index: 'imagen' ,name:'imagen', width:170, align:'center', sortable:false
				},{
					index: 'nombre' ,name:'nombre', width:340, align:'left', sortable:false
				},{
					index: 'duracion' ,name:'duracion', width:90, align:'center', sortable:false
				},{
					index: 'play' ,name:'play', width:50, align:'center', sortable:false
				},{
					index: 'remove' ,name:'remove', width:50, align:'center', sortable:false
				}]
				,onSelectRow: function(rowid, status) {
			    	$(this).find(".ui-state-highlight, [aria-selected='true']").removeClass('ui-state-highlight');
				}
				,gridComplete: function() {
					$(table).tableDnDUpdate();
				}
			});
			$("#subtabs").tabs( "refresh" );
		}
		function addNewList(){
			tipo_tab = 'nuevo';
			newTabDialog.dialog( "open" );
		}
		function changePosition(){
			var list = _playList['list_'+_selectPlayList];
			if(rowIndexSource != rowIndexTarget){
			    if (rowIndexTarget >= list.length) {
			        var k = rowIndexTarget - list.length;
			        while ((k--) + 1) {
			            list.push(undefined);
			        }
			    }
			    list.splice(rowIndexTarget, 0, list.splice(rowIndexSource, 1)[0]);
			}
		}
	</script>
	<script type="text/javascript">
		function isValidEmailAddress(emailAddress) {
		    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
		    return pattern.test(emailAddress);
		};
	</script>
	<script type="text/javascript">
		function sendEmail(){
			sendEmailMaster('shareSong');
		}
		function sendEmailList(){
			sendEmailMaster('sharePlayList');
		}
		function sendEmailMaster(type){
			var userFrom = txtUserFrom.val();
			var userTo = txtUserTo.val();
			var message = txtMessage.val();
			if(!isValidEmailAddress(userFrom)){
				$(function(){
					noty({
						text        : 'Debe ingresar un correo valido de origen',
						type        : 'error',
						dismissQueue: true,
						layout      : 'top',
						timeout		: 3000
					});
				});
			}
			if(!isValidEmailAddress(userTo)){
				$(function(){
					noty({
						text        : 'Debe ingresar un correo valido de destino',
						type        : 'error',
						dismissQueue: true,
						layout      : 'top',
						timeout		: 3000
					});
				});
			}
			var url_query = '<%=request.getAttribute("APP_SERVER_URL") %>'+type;
			if(userFrom != '' && userTo != ''){
				NProgress.start();
				$.ajax({
					type: "POST",
					url: url_query,
					dataType:"json",
					data:{
						by:'email',
						userFrom : userFrom,
						userTo : userTo,
						songID : share_link,
						listID : share_idList,
						message : message
					},
					cache: false,
					success: function(result, status){
						NProgress.done();
						$(function(){
							noty({
								text        : 'Se comparti&oacute; la cancion correctamente',
								type        : 'success',
								dismissQueue: true,
								layout      : 'top',
								modal		: true,
								timeout		: 3000
							});
						});
						$( "#shareEmailDIV" ).dialog( "close" );
					},
					error: function(data, status){
						$(function(){
							noty({
								text        : 'ocurrio un error [' + data.responseText + ']',
								type        : 'error',
								dismissQueue: true,
								layout      : 'top',
								modal		: true,
								timeout		: 3000
							});
						});
					},
                    progress: function(e) {
                        if(e.lengthComputable) {
                            var pct = (e.loaded / e.total) * 100;

                            NProgress.set(pct.toPrecision(3));
                        } else {
                            console.warn('Content Length not reported!');
                        }
                    }
				});
			}else{
				$(function(){
					noty({
						text        : 'Debe ingresar todos los datos',
						type        : 'error',
						dismissQueue: true,
						layout      : 'top',
						modal		: true,
						timeout		: 3000
					});
				});
			}
		}
		function registerFnc(){
			var username = txtUsernameRegister.val();
			if(!isValidEmailAddress(username)){
				$(function(){
					noty({
						text        : 'Debe ingresar un correo valido',
						type        : 'error',
						dismissQueue: true,
						layout      : 'top',
						modal		: true,
						timeout		: 3000
					});
				});
				return;
			}
			var password = txtPasswordRegister.val();
			var url_query = '<%=request.getAttribute("APP_SERVER_URL") %>getAccountID/?username='+username+'&password='+password;
			if(username != '' && password != ''){
				NProgress.start();
				$.ajax({
					type: "POST",
					url: url_query,
					dataType:"json",
					cache: false,
					success: function(result, status){
						NProgress.done();
						var estado = result.estado;
						$(function(){
							noty({
								text        : 'Se registraron los datos correctamente',
								type        : 'success',
								dismissQueue: true,
								layout      : 'top',
								modal		: true,
								timeout		: 3000
							});
						});
						registerDialog.dialog("close");
					},
					error: function(data, status){
						$(function(){
							noty({
								text        : 'Ocurrio un error [' + data.responseText + ']',
								type        : 'error',
								dismissQueue: true,
								layout      : 'top',
								modal		: true,
								timeout		: 3000
							});
						});
						registerDialog.dialog("close");
					},
                    progress: function(e) {
                        if(e.lengthComputable) {
                            var pct = (e.loaded / e.total) * 100;

                            NProgress.set(pct.toPrecision(3));
                        } else {
                            console.warn('Content Length not reported!');
                        }
                    }
				});
			}else{
				$(function(){
					noty({
						text        : 'Debe ingresar todos los datos',
						type        : 'error',
						dismissQueue: true,
						layout      : 'top',
						modal		: true,
						timeout		: 3000
					});
				});
			}
		}
		function loginFnc(){
			var username = txtUsername.val();
			if(!isValidEmailAddress(username)){
				$(function(){
					noty({
						text        : 'Debe ingresar un correo valido',
						type        : 'error',
						dismissQueue: true,
						layout      : 'top',
						modal		: true,
						timeout		: 3000
					});
				});
				return;
			}
			var password = txtPassword.val();
			if(username != '' && password != ''){
				execLogin(username, '', password, '', '');
			}else{
				$(function(){
					noty({
						text        : 'Debe ingresar todos los datos',
						type        : 'error',
						dismissQueue: true,
						layout      : 'top',
						modal		: true,
						timeout		: 3000
					});
				});
			}
		}
		function execLogin(username, facebookID, password, type, codigo){
			var url_query = '<%=request.getAttribute("APP_SERVER_URL") %>login/';
			NProgress.start();
			$.ajax({
				type: "POST",
				url: url_query,
				dataType:"json",
				data:{
					user : username,
					facebookID : facebookID,
					pass : password,
					type : type,
					codigo : codigo
				},
				cache: false,
				success: function(result, status){
					NProgress.done();
					var usuario = $.evalJSON(result.user);
					userInformation = usuario;
					userCode = usuario.CODE;
					$.cookie("_3tperu_cookie_userCode", userCode);
					// Login correcto
					$(function(){
						noty({
							text        : 'Login correcto',
							type        : 'success',
							dismissQueue: true,
							layout      : 'top',
							modal		: true,
							timeout		: 3000
						});
					});

					getCountSavedPlayList(userCode);
					_login = true;
					$('#user_username').html(usuario.EMAIL);
					userName = $.trim((usuario.FIRST_NAME != null ? usuario.FIRST_NAME : '') + ' ' + (usuario.LAST_NAME != null ? usuario.LAST_NAME : ''));
					$('#user_name').html(userName != '' ? userName : 'Usuario Invitado');
					$('#user_name').bind('click', function(){
						
					});
					$('#saveListTable').show();
					$( "#shared_h3" ).show();
					$dgShared.setGridParam({url:'<%=request.getAttribute("APP_SERVER_URL") %>getPlayListShared?userID='+getUserPart('EMAIL'),page:1}).trigger("reloadGrid");
					$( "#btnLogin" ).html('<img alt="Login" src="./images/logout.png" width="16" height="16" />Cerrar Sesi&oacute;n');
					loginDialog.dialog("close");
				},
				error: function(data, status){
					NProgress.done();
					var result = $.evalJSON(data.responseText);
					var errorCode = result.errorCode;
					var message = result.message;
					if(errorCode == '0'){
						// Usuario no existe
						$(function(){
							noty({
								text        : 'El usuario ingresado no es v&aacute;lido',
								type        : 'warning',
								dismissQueue: true,
								layout      : 'top',
								modal		: true,
								timeout		: 3000
							});
						});
					}
					if(errorCode == '1'){
						// Password incorrecto
						$(function(){
							noty({
								text        : 'Contrase&ntilde;a incorrecta',
								type        : 'warning',
								dismissQueue: true,
								layout      : 'top',
								modal		: true,
								timeout		: 3000
							});
						});
					}
					loginDialog.dialog("close");
				},
                progress: function(e) {
                    if(e.lengthComputable) {
                        var pct = (e.loaded / e.total) * 100;

                        NProgress.set(pct.toPrecision(3));
                    } else {
                        console.warn('Content Length not reported!');
                    }
                }
			});
		}
		function logoutFnc(){
			$( "#btnLogin" ).html('<img alt="Login" src="./images/login_key.png" width="16" height="16" />Usuario');
			_login = false;
			$('#saveListTable').hide();
			userCode = -1;
			$('#user_username').html('Default');
			$('#user_name').html('Usuario Invitado');
			$( "#div-options" ).accordion({ active: 0 });
			$( "#shared_h3" ).hide();
			$.cookie("_3tperu_cookie_userCode", userCode);
		}
		function getCountSavedPlayList(code){
			var url_query = '<%=request.getAttribute("APP_SERVER_URL") %>countPlayListFromUser/?userID='+code;
			$("#messageDIV").html('<p>Verificando Listas</p>');
			$("#messageDIV").dialog('open');
			NProgress.start();
			$.ajax({
				type: "POST",
				url: url_query,
				dataType:"json",
				cache: false,
				success: function(result, status){
					NProgress.done();
					$("#messageDIV").dialog('close');
					var cantidad = parseInt(result);
					if(cantidad > 0){
						_numberList = cantidad;
						getSavedPlayList(code);
					}else{
						$(function(){
							noty({
								text        : 'Usted no tiene listas grabadas',
								type        : 'error',
								dismissQueue: true,
								layout      : 'top',
								modal		: true,
								timeout		: 3000
							});
						});					
					}
				},
				error: function(data, status){
					NProgress.done();
					$("#messageDIV").dialog('close');
						$(function(){
							noty({
								text        : 'Ocurri&oacute; un error al intentar cargar las listas',
								type        : 'error',
								dismissQueue: true,
								layout      : 'top',
								modal		: true,
								timeout		: 3000
							});
						});
				},
                progress: function(e) {
                    if(e.lengthComputable) {
                        var pct = (e.loaded / e.total) * 100;

                        NProgress.set(pct.toPrecision(3));
                    } else {
                        console.warn('Content Length not reported!');
                    }
                }
			});
		}
		function saveAllPlayList(){
			$("#messageDIV").html('<p>Se proceder&aacute; a almacenar sus listas</p>');
			$("#messageDIV").dialog('open');
			var url_query = '<%=request.getAttribute("APP_SERVER_URL") %>saveAllPlayList/';
			var index = 0;
			var data = new Array();
			$.each( _playList, function( key, value ) {
				var item = {};
				var songList = new Array();

				var playList = _playList['list_'+index];
				var name = _listnames[index];
				var code = _codeList[index];
				
				for(var j = 0; j < playList.length; j++){
					var song = {};
					song['code'] = playList[j].code;
					song['order'] = j;
					song['link'] = playList[j].link;
					songList.push(song);
				}
				// Build item
				item['code'] = code;
				item['name'] = name;
				item['songList'] = songList;

				data.push(item);
				index = index + 1;
			});
			NProgress.start();
			$.ajax({
				type: "POST",
				url: url_query,
				data: {
					userID : userCode,
					info : $.toJSON(data)
				},
				dataType:"json",
				cache: false,
				success: function(result, status){
					NProgress.done();
					var ncodeList = new Array();
					for(var i = 0; i < result.length; i++){
						var item = result[i];
						var playList = _playList['list_'+i];
						ncodeList.push(item['playList']);

						var songListCode = result['songList'];
						for(var j = 0; j < playList.length; j++){
							playList[j].code = songListCode[j];
						}
					}
					_codeList = ncodeList;
					$("#messageDIV").dialog('close');
					$(function(){
						noty({
							text        : 'Se logr&oacute; almacenar las listas satisfactoriamente',
							type        : 'success',
							dismissQueue: true,
							layout      : 'top',
							modal		: true,
							timeout		: 3000
						});
					});
				},
				error: function(data, status){
					NProgress.done();
					$("#messageDIV").dialog('close');
					$(function(){
						noty({
							text        : 'Ocurri&oacute; un error al intentar grabar las listas',
							type        : 'error',
							dismissQueue: true,
							layout      : 'top',
							modal		: true,
							timeout		: 3000
						});
					});
				},
                progress: function(e) {
                    if(e.lengthComputable) {
                        var pct = (e.loaded / e.total) * 100;

                        NProgress.set(pct.toPrecision(3));
                    } else {
                        console.warn('Content Length not reported!');
                    }
                }
			});
		}
		function savePlayList(index){
			var url_query = '<%=request.getAttribute("APP_SERVER_URL") %>savePlayList/';
			var playList = _playList['list_'+index];
			var name = _listnames[index];
			var code = _codeList[index];

			$("#messageDIV").html('<p>Se proceder&aacute; a almacenar la lista ['+name+']</p>');
			$("#messageDIV").dialog('open');
			var data = {};
			var songList = new Array();

			for(var i = 0; i < playList.length; i++){
				var song = {};
				song['code'] = playList[i].code;
				song['order'] = i;
				song['link'] = playList[i].link;
				songList.push(song);
			}
			// Build item
			data['code'] = code;
			data['name'] = name;
			data['songList'] = songList;

			NProgress.start();
			$.ajax({
				type: "POST",
				url: url_query,
				data: {
					userID : userCode,
					info : $.toJSON(data)
				},
				dataType:"json",
				cache: false,
				success: function(result, status){
					NProgress.done();
					var songListCode = result['songList'];
					_codeList[index] = result['playList'];
					for(var i = 0; i < playList.length; i++){
						playList[i].code = songListCode[i];
					}
					$("#messageDIV").dialog('close');
					$(function(){
						noty({
							text        : 'Se logr&oacute; almacenar la lista satisfactoriamente',
							type        : 'success',
							dismissQueue: true,
							layout      : 'top',
							modal		: true,
							timeout		: 3000
						});
					});
				},
				error: function(data, status){
					NProgress.done();
					$("#messageDIV").dialog('close');
					$(function(){
						noty({
							text        : 'Ocurri&oacute; un error al intentar grabar la lista',
							type        : 'error',
							dismissQueue: true,
							layout      : 'top',
							modal		: true,
							timeout		: 3000
						});
					});
				},
                progress: function(e) {
                    if(e.lengthComputable) {
                        var pct = (e.loaded / e.total) * 100;

                        NProgress.set(pct.toPrecision(3));
                    } else {
                        console.warn('Content Length not reported!');
                    }
                }
			});
		}
		function getSavedPlayList(code){
			var url_query = '<%=request.getAttribute("APP_SERVER_URL") %>getPlayListFromUser/?userID='+code;
			$("#messageDIV").html('<p>Cargando Listas Guardadas</p>');
			$("#messageDIV").dialog('open');

			NProgress.start();
			$.ajax({
				type: "POST",
				url: url_query,
				dataType:"json",
				cache: false,
				success: function(result, status){
					NProgress.done();
					$("#messageDIV").dialog('close');
					var list = result;
					clearTabs();
					for(var i = 0; i < list.length; i++){
						var listname = list[i].LIST_NAME;
						var codeList = list[i].CODE;
						var songList = list[i].SONG_LIST;
						if(_listnames[i] == undefined || _listnames[i] == ''){
							_listnames.push(listname);
						}else{
							_listnames[i] = listname;
						}
						if(_codeList[i] == undefined || _codeList[i] == ''){
							_codeList.push(codeList);
						}else{
							_codeList[i] = codeList;
						}

						var nlist = new Array();
						for(var j = 0; j < songList.length; j++){
							var item = {};
							var actual = songList[j];
							item['codigo'] = 'http://gdata.youtube.com/feeds/api/videos/'+actual.codigo;
							item['code'] = actual.code;
							item['link'] = actual.link;
							item['nombre'] = actual.title;
							item['imagen'] = "<img width=\"120\" heigth=\"100\" src=\""+actual.image_link+"\">";
							var segundos = parseInt(actual.segundos);
							item['segundos'] = segundos;
							item['duracion'] = $.jPlayer.convertTime(segundos);
							item['agregar'] = "<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Agregar\" onclick=\"javascript:addToPlayList('"+j+"')\"><span class=\"ui-icon ui-icon-plusthick\"></span></li></ul>";
							item['play'] = "<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Escuchar\" onclick=\"javascript:play('"+j+"')\"><span class=\"ui-icon ui-icon-play\"></span></li></ul>";
							item['remove'] = "<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Quitar\" onclick=\"javascript:removeFromPlayList("+j+")\"><span class=\"ui-icon ui-icon-trash\"></span></li></ul>";
							
							nlist.push(item);
						}
						_playList['list_'+i] = nlist;
						addList(i);
					}
					$("#subtabs").tabs( "refresh" );
				},
				error: function(data, status){
					NProgress.done();
					$("#messageDIV").dialog('close');
					$(function(){
						noty({
							text        : 'Ocurri&oacute; un error al intentar cargar las listas',
							type        : 'error',
							dismissQueue: true,
							layout      : 'top',
							modal		: true,
							timeout		: 3000
						});
					});
				},
                progress: function(e) {
                    if(e.lengthComputable) {
                        var pct = (e.loaded / e.total) * 100;

                        NProgress.set(pct.toPrecision(3));
                    } else {
                        console.warn('Content Length not reported!');
                    }
                }
			});
		}
	</script>
	<script type="text/javascript">
		function drawPlayList(){
			var listname = 'list_'+_selectPlayList;
			var list = _playList[listname] ? _playList[listname] : [];
			var gridname = "#data-grid-local-"+_selectPlayList;
			if($( gridname )){
				try{
					$( gridname ).jqGrid('clearGridData');
				}catch(e){}
			}
			
			for(var i = 0; i <= list.length; i++) {
				$( gridname ).jqGrid('addRowData', i+1 ,list[i]); 
			}
		}
	</script>
	<script type="text/javascript">
		function drawTableResult(){
			if($dgBuscar){
				try{
					$dgBuscar.jqGrid('clearGridData');
				}catch(e){}
			}

			for(var i = 0; i <= _data.length; i++) {
				$dgBuscar.jqGrid('addRowData', i+1 ,_data[i]); 
			}
		}
	</script>
	<script type="text/javascript">
		var actual = -1;
		function showBuscar(){
			$('#search_info').show();
			$('#q').focus();
			$( "#h_buscar").html('Buscador de Canciones');
			$( "#div-options" ).accordion({ active: 1 });
		}
		function buscar(){
			var vq = $('#q').val();
			_data = [];
			if(vq != ''){
				var url_query ='<%=request.getAttribute("APP_SERVER_URL") %>search/?vq='+vq+'&start-index=1&max-results=10';
				execURL(url_query);
			}else{
				$(function(){
					noty({
						text        : 'Debe ingresar un termino para buscar',
						type        : 'error',
						dismissQueue: true,
						layout      : 'top',
						modal		: true,
						timeout		: 3000
					});
				});
			}
		}
		function related(video_link){
			$('#search_info').hide();
			$( "#h_buscar").html('Canciones Relacionadas');
			$( "#div-options" ).accordion({ active: 1 });
			var url_query ='<%=request.getAttribute("APP_SERVER_URL") %>related/?url='+video_link+'&start-index=1&max-results=10';
			if($dgBuscar){
				try{
					$dgBuscar.jqGrid('clearGridData');
				}catch(e){}
			}
			execURLRelated(url_query);
		}
		$("#q").keypress(function(event) {
  			if ( event.which == 13 ) {
				buscar();
			}else{
				if ( event.keyCode == 13 ){
					buscar();
				}else{
					if ( event.charCode == 13 ){
						buscar();
					}
				}
			}
		});
		function limpiar(){
			if($dgBuscar){
				$dgBuscar.jqGrid('clearGridData');
				$('#search-previous-up').html('');
				$('#search-next-up').html('');

				$('#search-previous-down').html('');
				$('#search-next-down').html('');
			}
			$('#q').val('');
			$('#q').focus();
		}
		function execURLRelated(url_query){
			_data = [];
			$("#messageDIV").html('<center><img alt="waiting..." src="./images/loading.gif" height="134" width="231"></center>');
			$("#messageDIV").dialog('open');

			NProgress.start();
			$.ajax({
				type: "GET",
				url: url_query,
				dataType:"json",
				cache: false,
				success: function(result, status){
					NProgress.done();
					var previous = result.previous;
					var next = result.next;

					var prev_up = $('#search-previous-up');
					var nxt_up = $('#search-next-up');

					var prev = $('#search-previous-down');
					var nxt = $('#search-next-down');

					if(previous == ''){
						prev.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-w\" title=\"Anterior\"><span class=\"ui-icon ui-icon-circle-arrow-w\"></span>Anterior</li></ul>');
						prev_up.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-w\" title=\"Anterior\"><span class=\"ui-icon ui-icon-circle-arrow-w\"></span>Anterior</li></ul>');
					}else{
						prev.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-w\" title=\"Anterior\" onclick="javascript:execURLRelated(\'' + previous + '\');"><span class=\"ui-icon ui-icon-circle-arrow-w\"></span><b>Anterior</b></li></ul>');
						prev_up.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-w\" title=\"Anterior\" onclick="javascript:execURLRelated(\'' + previous + '\');"><span class=\"ui-icon ui-icon-circle-arrow-w\"></span><b>Anterior</b></li></ul>');
					}
					if(next == ''){
						nxt.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-e\" title=\"Anterior\"><span class=\"ui-icon ui-icon-circle-arrow-e\"></span>Siguiente</li></ul>');
						nxt_up.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-e\" title=\"Anterior\"><span class=\"ui-icon ui-icon-circle-arrow-e\"></span>Siguiente</li></ul>');
					}else{
						nxt.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-e\" title=\"Anterior\" onclick="javascript:execURLRelated(\'' + next + '\');"><span class=\"ui-icon ui-icon-circle-arrow-e\"></span><b>Siguiente</b></li></ul>');
						nxt_up.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-e\" title=\"Anterior\" onclick="javascript:execURLRelated(\'' + next + '\');"><span class=\"ui-icon ui-icon-circle-arrow-e\"></span><b>Siguiente</b></li></ul>');
					}
					var entries = result['entry'];
					for(var i = 0; i < entries.length; i++){
						var _entry = entries[i];
						var vid = _entry.vid;
						var id = _entry.id;
						var title = _entry.title;
						var img = _entry.img;
						var segundos = parseInt(_entry.segundos);
						var _duracion = $.jPlayer.convertTime(segundos);
						var item = {
							codigo : id,
							code : -1,
							link : vid,
							nombre : title,
							imagen : '<img width=\"120\" heigth=\"100\" src=\"' + img + '\">',
							segundos : segundos,
							duracion : _duracion,
							agregar : '<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Agregar\" onclick=\"javascript:addToPlayList(\''+i+'\')\"><span class=\"ui-icon ui-icon-plusthick\"></span></li></ul>'
						};
						_data.push(item);
					}
					drawTableResult();
					$("#messageDIV").dialog('close');
				},
				error: function(data, status){
					NProgress.done();
					$(function(){
						noty({
							text        : 'ocurrio un error ['+data.responseText+']',
							type        : 'error',
							dismissQueue: true,
							layout      : 'top',
							modal		: true,
							timeout		: 3000
						});
					});
					$("#messageDIV").dialog('close');
				},
                progress: function(e) {
                    if(e.lengthComputable) {
                        var pct = (e.loaded / e.total) * 100;

                        NProgress.set(pct.toPrecision(3));
                    } else {
                        console.warn('Content Length not reported!');
                    }
                }
			});
		}
		function execURL(url_query){
			_data = [];
			$("#messageDIV").html('<center><img alt="waiting..." src="./images/loading.gif" height="134" width="231"></center>');
			$("#messageDIV").dialog('open');

			NProgress.start();
			$.ajax({
				type: "GET",
				url: url_query,
				dataType:"jsonp",
				cache: false,
				success: function(result, status){
					NProgress.done();
					var previous = '';
					var next = '';
					var links = $(result).find('link');

					var prev_up = $('#search-previous-up');
					var nxt_up = $('#search-next-up');

					var prev = $('#search-previous-down');
					var nxt = $('#search-next-down');

					for(var i = 0; i < links.length; i++){
						if(links[i].rel == 'previous'){
							previous = links[i].href;
								break;
						}
					}
					for(var i = 0; i < links.length; i++){
						if(links[i].rel == 'next'){
							next = links[i].href;
							break;
						}
					}

					if(previous == ''){
						prev.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-w\" title=\"Anterior\"><span class=\"ui-icon ui-icon-circle-arrow-w\"></span>Anterior</li></ul>');
						prev_up.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-w\" title=\"Anterior\"><span class=\"ui-icon ui-icon-circle-arrow-w\"></span>Anterior</li></ul>');
					}else{
						prev.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-w\" title=\"Anterior\" onclick="javascript:execURL(\'' + previous + '\');"><span class=\"ui-icon ui-icon-circle-arrow-w\"></span><b>Anterior</b></li></ul>');
						prev_up.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-w\" title=\"Anterior\" onclick="javascript:execURL(\'' + previous + '\');"><span class=\"ui-icon ui-icon-circle-arrow-w\"></span><b>Anterior</b></li></ul>');
					}
					if(next == ''){
						nxt.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-e\" title=\"Anterior\"><span class=\"ui-icon ui-icon-circle-arrow-e\"></span>Siguiente</li></ul>');
						nxt_up.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-e\" title=\"Anterior\"><span class=\"ui-icon ui-icon-circle-arrow-e\"></span>Siguiente</li></ul>');
					}else{
						nxt.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-e\" title=\"Anterior\" onclick="javascript:execURL(\'' + next + '\');"><span class=\"ui-icon ui-icon-circle-arrow-e\"></span><b>Siguiente</b></li></ul>');
						nxt_up.html('<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-icon-circle-arrow-e\" title=\"Anterior\" onclick="javascript:execURL(\'' + next + '\');"><span class=\"ui-icon ui-icon-circle-arrow-e\"></span><b>Siguiente</b></li></ul>');
					}
					$(result).find("entry").each(function(index, value){
							var vid = '';
							var id = $(this).children('id').text();
							var title = $(this).find('media\\:title').first().text();
							var vid = $(this).find('media\\:player').first().attr("url");
							var images = $(this).find('media\\:thumbnail').first();
							var video = $(this).find('media\\:content').first();
							var img = images.attr("url");
							var segundos = parseInt(video.attr("duration"));
							var _duracion = $.jPlayer.convertTime(segundos);
							var item = {
								codigo : id,
								code : -1,
								link : vid,
								nombre : title,
								imagen : '<img width=\"120\" heigth=\"100\" src=\"' + img + '\">',
								segundos : segundos,
								duracion : _duracion,
								agregar : '<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Agregar\" onclick=\"javascript:addToPlayList(\''+index+'\')\"><span class=\"ui-icon ui-icon-plusthick\"></span></li></ul>'
							};
							_data.push(item);
					});
					drawTableResult();
					$("#messageDIV").dialog('close');
				},
				error: function(data, status){
					NProgress.done();
					$(function(){
						noty({
							text        : 'ocurrio un error ['+data.responseText+']',
							type        : 'error',
							dismissQueue: true,
							layout      : 'top',
							modal		: true,
							timeout		: 3000
						});
					});
					$("#messageDIV").dialog('close');
				},
                progress: function(e) {
                    if(e.lengthComputable) {
                        var pct = (e.loaded / e.total) * 100;

                        NProgress.set(pct.toPrecision(3));
                    } else {
                        console.warn('Content Length not reported!');
                    }
                }
			});
		}
		function addToPlayList(index){
			addToPlayListMaster(index, _selectPlayList);
		}
		function addToPlayListMaster(index, playListNumber){
			var list = _playList['list_'+playListNumber] ? _playList['list_'+playListNumber]: [];
			var item = _data[index];
			$("#messageDIV").html('<center><img alt="waiting..." src="./images/loading.gif" height="134" width="231"></center>');
			$("#messageDIV").dialog('open');

			NProgress.start();
			$.ajax({
				type: "POST",
				url: '<%=request.getAttribute("APP_SERVER_URL") %>verifyMP3/',
				cache: false,
				data: {
					url: item.link
				},
				success: function(_data){
					var status = _data.estado;
					var msg = _data.responseText;
					NProgress.done();
					$("#messageDIV").dialog('close');
					item.play = '<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Escuchar\" onclick=\"javascript:play(' + list.length + ')\"><span class=\"ui-icon ui-icon-play\"></span></li></ul>';
					item.remove = '<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Quitar\" onclick=\"javascript:removeFromPlayList(' + list.length + ')\"><span class=\"ui-icon ui-icon-trash\"></span></li></ul>';
					list.push(item);
					_playList['list_'+playListNumber] = list;
					drawPlayList();
					$("#messageDIV").html('<p>Se adiciono la cancion satisfactoriamente a su lista...</p>');
					$("#messageDIV").dialog('open').delay('1000').queue(function(){
																		   $("#messageDIV").dialog('close');
																		   $(this).dequeue();
																		});
					if(status == 'WAIT'){
						$("#messageDIV").html('<p>'+msg+'...</p>');
						$("#messageDIV").dialog('open').delay('1000').queue(function(){
																			   $("#messageDIV").dialog('close');
																			   $(this).dequeue();
																			});
					}
				},
				error: function(data, status){
					NProgress.done();
					$("#messageDIV").dialog('close');
					$(function(){
						noty({
							text        : 'ocurrio un error al validar el archivo ['+data.responseText+']',
							type        : 'error',
							dismissQueue: true,
							layout      : 'top',
							modal		: true,
							timeout		: 3000
						});
					});
				},
                progress: function(e) {
                    if(e.lengthComputable) {
                        var pct = (e.loaded / e.total) * 100;

                        NProgress.set(pct.toPrecision(3));
                    } else {
                        console.warn('Content Length not reported!');
                    }
                }
			});
		}
		function saveUserDetail(){
			$( "#userDetailDIV" ).dialog( "close" );
		}
		function removeFromPlayList(index){
			removeFromPlayListMaster(index,_selectPlayList);
		}
		function removeFromPlayListMaster(index, playListNumber){
			tipo_eliminar = function(){
				var list = _playList['list_'+playListNumber] ? _playList['list_'+playListNumber] : [];
				var nList = [];
				if(list){
					item = list[index];
					if(item.code != -1){
						NProgress.start();
						$.ajax({
							type: "POST",
							url: '<%=request.getAttribute("APP_SERVER_URL") %>deleteSong/',
							cache: false,
							data: {
								songID: item.code
							},
							success: function(data, status){
								NProgress.done();
								$("#messageDIV").dialog('close');
							},
							error: function(data, status){
								NProgress.done();
								$("#messageDIV").dialog('close');
								$(function(){
									noty({
										text        : 'ocurrio un error al validar el archivo ['+data.responseText+']',
										type        : 'error',
										dismissQueue: true,
										layout      : 'top',
										modal		: true,
										timeout		: 3000
									});
								});
							},
		                    progress: function(e) {
		                        if(e.lengthComputable) {
		                            var pct = (e.loaded / e.total) * 100;
		
		                            NProgress.set(pct.toPrecision(3));
		                        } else {
		                            console.warn('Content Length not reported!');
		                        }
		                    }
						});
					}
					list.splice(index, 1);
					for(var i = 0; i < list.length; i++){
						var item = list[i];
						item.play = '<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Escuchar\" onclick=\"javascript:play(' + i + ')\"><span class=\"ui-icon ui-icon-play\"></span></li></ul>';
						item.remove = '<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Quitar\" onclick=\"javascript:removeFromPlayList(' + i + ')\"><span class=\"ui-icon ui-icon-trash\"></span></li></ul>';
						nList.push(item);
					}
					list = nList;
					_playList['list_'+playListNumber] = list;
					drawPlayList();
				}
			};
			$("#confirmDIV").dialog('open');
		}
		function showChangeList(index){
			var listShow = new Array();
			change['song'] = index;
			if(_listnames.length > 1){
				for(var i = 0; i < _listnames.length; i++){
					if(_selectPlayList != i){
						var item = {};
						item['index'] = i;
						item['label'] = _listnames[i];
						listShow.push(item);
					}
				}
			}
			if(listShow.length > 0){
				$("#changeListControl li.ui-widget-content").remove();
				for(var i = 0; i < listShow.length; i++){
					var item = listShow[i];
					$("#changeListControl").append( $('<li/>', {id: "codigo_" + item.index, text: item.label, class: 'ui-widget-content' }));
				}
				$( "#changeListDIV" ).dialog('open');
			}
		}
		function completeChange(){
			var source = _playList['list_'+change['source']];
			var target = _playList['list_'+change['target']];
			if(!target){
				_playList['list_'+change['target']] = new Array();
				target = _playList['list_'+change['target']];
			}
			var song = source[change['song']];

			var nList = [];
			if(source){
				source.splice(change['song'], 1);
				for(var i = 0; i < source.length; i++){
					var item = source[i];
					item.play = '<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Escuchar\" onclick=\"javascript:play(' + i + ')\"><span class=\"ui-icon ui-icon-play\"></span></li></ul>';
					item.remove = '<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\"><li class=\"ui-state-default ui-corner-all\" title=\"Quitar\" onclick=\"javascript:removeFromPlayList(' + i + ')\"><span class=\"ui-icon ui-icon-trash\"></span></li></ul>';
					nList.push(item);
				}
				source = nList;
			}
			target.push(song);
			clearTabs();

			var index = 0;
			$.each( _playList, function( key, value ) {
				addList(index);
				index = index + 1;
			});
		}
		function play(index){
			var list = _playList['list_'+_selectPlayList] ? _playList['list_'+_selectPlayList] : [];
			actual = index;
			var item = list[index];
			var mp3 = '<%=request.getAttribute("APP_SERVER_URL") %>mp3low/?url=' + item.link;
			$("#waiting_play").html('<img alt="waiting..." src="./images/waiting.gif" height="30" width="30">');
			$("#playing_image").html('<img width="120" height="100" src="./images/no_file_music.png">');
			image_played = item.imagen;
			$("#jquery_jplayer_1").jPlayer("setMedia", {
				mp3: mp3
			});
			$("#jquery_jplayer_1").jPlayer("play");
			showTitle(item.nombre);
		}
		function getPreviousSong(){
			if(repeat.is(':checked')){
				$("#jquery_jplayer_1").jPlayer("play");
			}else{
				if(shuffle.is(':checked')){
					var listSize = _playList['list_'+_selectPlayList];
					var number = actual;
					while(number == actual){
						number = 1 + Math.floor(Math.random() * listSize.length);
					}
					play(number);
				}else{
					findPreviousSong();
				}
			}
		}
		function getNextSong(){
			if(repeat.is(':checked')){
				$("#jquery_jplayer_1").jPlayer("play");
			}else{
				if(shuffle.is(':checked')){
					var listSize = _playList['list_'+_selectPlayList];
					var number = actual;
					while(number == actual){
						number = 1 + Math.floor(Math.random() * listSize.length);
					}
					play(number);
				}else{
					findNextSong();
				}
			}
		}
		function findNextSong(){
			var list = _playList['list_'+_selectPlayList] ? _playList['list_'+_selectPlayList] : [];
			actual ++;
			if(actual >= list.length){
				actual = 0;
			}
			play(actual);
		}
		function findPreviousSong(){
			var list = _playList['list_'+_selectPlayList] ? _playList['list_'+_selectPlayList] : [];
			actual --;
			if(actual < 0){
				actual = list.length;
			}
			play(actual);
		}
		function showTitle(text){
			var div = $('#jp-title');
			div.html('<ul><li>' + text + '</li></ul>');
		}
		$( "#btnLogin" ).html('<img alt="Login" src="./images/login_key.png" width="16" height="16" />Usuario');
		if(userCode != -1){
			execLogin('', '', '', '', userCode);
			$('#saveListTable').show();
			$( "#btnLogin" ).html('<img alt="Login" src="./images/logout.png" width="16" height="16" />Cerrar Sesi&oacute;n');
		}
	</script>
  </body>
</html>